package org.ehe.erp.mapper.product;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.ehe.common.mybatis.core.mapper.BaseMapperPlus;
import org.ehe.erp.domain.product.ErpMaterial;
import org.ehe.erp.domain.product.vo.ErpMaterialVo;

/**
 * @author :zhangnn
 * @className :MaterialMapper
 * @description: TODO
 * @date 2025-09-08 14:30:34
 */
public interface MaterialMapper extends BaseMapperPlus<ErpMaterial, ErpMaterialVo> {

    /**
     * 检查编码是否存在
     */
    @Select("SELECT COUNT(*) FROM erp_material " +
        "WHERE material_code = #{materialCode} AND tenant_id = #{tenantId} AND del_flag = 0 " +
        "AND (#{excludeId} IS NULL OR id != #{excludeId})")
    int checkCodeExists(@Param("materialCode") String materialCode,
                        @Param("tenantId") String tenantId,
                        @Param("excludeId") Long excludeId);

    /**
     * 检查名称是否存在
     */
    @Select("SELECT COUNT(*) FROM erp_material " +
        "WHERE material_name = #{materialName} AND tenant_id = #{tenantId} AND del_flag = 0 " +
        "AND (#{excludeId} IS NULL OR id != #{excludeId})")
    int checkNameExists(@Param("materialName") String materialName,
                        @Param("tenantId") String tenantId,
                        @Param("excludeId") Long excludeId);

    /**
     * 获取下一个可用编码
     */
    @Select("SELECT LPAD(IFNULL(MAX(CAST(material_code AS UNSIGNED)), 0) + 1, 2, '0') " +
        "FROM erp_material WHERE tenant_id = #{tenantId} AND del_flag = 0")
    String getNextCode(@Param("tenantId") String tenantId);
}
